﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Data;
using CoreEx.Common.Proxy;
using CoreEx.DynamicInvoker;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;



namespace CoreEx.Database.Client.Implementation
{
    
    
    public class ParameterExtractor : IParameterExtractor,IInitialize
    {
        private IServiceContainer _serviceContainer;
        public IEnumerable<IDataParameter> GetParameters(string procedureName)
        {
            try
            {
                Connection.Open();
                var connectionName = ((IDbConnectionInfo) Connection).Name;
                var providerFactory = _serviceContainer.GetService<DbProviderFactory>(connectionName);
                var commandBuilder = providerFactory.CreateCommandBuilder();
                var command = (IDbCommand)((IActualTarget)Connection.CreateCommand()).Instance;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = procedureName;
                commandBuilder.GetType().DynamicInvoke("DeriveParameters", new[] {command});
                return command.Parameters.Cast<IDataParameter>();
            }
            finally
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();
            }
        }

        public IDbConnection Connection { get; set; }

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}
